//
//  TenderInfoController.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2019/12/31.
//  Copyright © 2019 zwb. All rights reserved.
//

import UIKit
import WebKit
import Kingfisher
import AVFoundation
var timeflagH:CGFloat = 40
class ZyaTenderInfoVC: UIViewController,getDepositRemainable {
   
    lazy var timeflagView:ZyaTimeFlagView = {
        let v = ZyaTimeFlagView()
        return v
    }()
    lazy var tbinfo_V: TbInfoNewView = {
        
        var v = TbInfoNewView()
      
        return v
        
        
    }()
  
    lazy var jpTitleView:TitleChujiaImgView = {
        let v = TitleChujiaImgView( withImg: true)
        return v
    }()
    lazy var zbTitleView:TitleChujiaImgView = {
        let v = TitleChujiaImgView( withImg: false)
        return v
    }()
    var depositRemain = 0.0
    var processid = ""
    var enterType = ZyaEnterType.none
    var todoType = ZyaTodoType.normal
    
    
    lazy var tableView: UITableView = {
        let v = UITableView()
        return v
    }()
    
    var webHeight:Double?
    var imgHeight:Double?
    
    var headView = UIView()
    
    
    lazy var zbInstructions:UILabel = {
        let lab :UILabel = UILabel()
        lab.font = UIFont.systemFont(ofSize: 15)
        lab.backgroundColor = .white
        lab.textAlignment = .center
        lab.text = "采购说明"
        return lab
    }()
    lazy var zbLine:UIView = {
        let view:UIView = UIView()
        view.backgroundColor = #colorLiteral(red: 0.7764705882, green: 0.7764705882, blue: 0.7843137255, alpha: 1)
        
        return view
    }()
    var btnflag = "1"
    
    var webV: WKWebView = {
        let web = WKWebView()
        return web
    }()
    
    lazy var bottomView: UIView = {
        let view:UIView = UIView()
        view.backgroundColor = .white
        let line = UIView(frame: CGRect(x:0,y:0,width: KSGlobal.screenW,height: 1))
        line.backgroundColor = #colorLiteral(red: 0.6039215686, green: 0.6039215686, blue: 0.6039215686, alpha: 1)
        view.addSubview(line)
        return view
    }()
    
    private var zbFiles = [ZyaZbFile]()
    
    lazy var btn_mark:ZyaOpButton = {
        var btn1 = ZyaOpButton()
        btn1.setTitle("收藏", for: .normal)
        btn1.addTarget(self, action: #selector(markAction), for: .touchUpInside)
        if let shoucang = UIImage(named:"shoucang") {
            btn1.setImage(shoucang, for: .normal)
        }
        return btn1
    }()
 
    lazy var btn_feedback:ZyaOpButton = {
        var btn_down = ZyaOpButton()
        btn_down.setTitle("反馈", for: .normal)
        btn_down.addTarget(self, action: #selector(feedbackAction), for: .touchUpInside)
        if let xiazai = UIImage(named:"feedback1") {
            btn_down.setImage(xiazai, for: .normal)
        }
        return btn_down
    }()
    lazy var btn_call:ZyaOpButton = {
        
        var btn_call = ZyaOpButton()
        btn_call.setTitle("电话", for: .normal)
        btn_call.addTarget(self, action: #selector(phoneAction(sender:)), for: .touchUpInside)
        if let phone = UIImage(named:"phone") {
            btn_call.setImage(phone, for: .normal)
        }
        return btn_call
    }()
    lazy var btn_tb:ZyaActionButton = {
        var btn_tb = ZyaActionButton()
        return btn_tb
    }()
    var idkey:String = ""
    var originalMark:String?
    var innerType:ZTBInnerType?
    
    private var one = ZyaZtbContentModel(JSON:["":""])!
    private let helper = ZyaTenderHelper()
 

    
    var listType = TBandJPType.TB
     
    
    init(listType:TBandJPType) {
        super.init(nibName: nil, bundle: nil)
        self.listType = listType
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
   
    var isTranslucent_ori:Bool? // 本控件需要操作，但是又不希望影响到其他的控件
    var btnName = ""
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 收藏按钮状态在页面内被改变，退出时检测到做收藏接口改变操作
        if self.one.ztbMark != self.originalMark {
            self.helper.setRecordMark(z_record_id:self.idkey,z_mark:self.one.ztbMark.unwrap,z_type:self.listType == .TB ? "zhaobiao" : "jingpai")
            
        }
        if let trat = isTranslucent_ori {
            self.navigationController?.navigationBar.isTranslucent = trat
        }
        
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
      
          
        
    }
   
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
     
        // 防止位置会下移一个导航的高度
        isTranslucent_ori = self.navigationController?.navigationBar.isTranslucent
        self.navigationController?.navigationBar.isTranslucent = true
        self.insertIds2Update()
    }
    deinit {
        KSLog("info销毁")
      
        NotificationCenter.default.removeObserver(self)
    
       
    }
    
    var bottomH:CGFloat = 60
    override func viewDidLoad() {
        super.viewDidLoad()
       
    
        
        self.title = "详情"
        self.view.backgroundColor = .white
        
        let navH = self.navigationController.isSome ? self.navigationController!.navigationBar.frame.height : 0
       var topH = UIApplication.shared.statusBarFrame.height + navH
 
        view.addSubview(timeflagView)
      
        self.view.addSubview(tableView)
        view.addSubview(bottomView)
        timeflagView.frame = CGRect(x:0,y: topH,width: self.view.frame.width,height:  timeflagH)

 
        bottomView.frame = CGRect(x:0,y: view.ks_maxY - bottomH,width: self.view.frame.width,height:  bottomH)

        tableView.frame = CGRect(x:0,y: timeflagView.ks_maxY,width: self.view.frame.width,height:  bottomView.ks_y - timeflagView.ks_maxY)

 
     
       
        
        headView.addSubview(tbinfo_V)
        headView.addSubview(zbLine)
        headView.addSubview(zbInstructions)
        headView.isUserInteractionEnabled = true
        headView.frame = CGRect(x:0,y:0,width:KSGlobal.screenW,height: 600)
        self.tableView.tableHeaderView = headView
        jpTitleView.listType = self.listType
        if listType == .JP {
            headView.addSubview(jpTitleView)
            zbInstructions.text = "销售说明"
            jpTitleView.snp.makeConstraints { (make) in
                make.left.equalToSuperview()
                make.right.equalToSuperview()
                make.top.equalTo(headView)
            }
        } else {
            headView.addSubview(zbTitleView)
            zbInstructions.text = "采购说明"
            zbTitleView.snp.makeConstraints { (make) in
                make.left.equalToSuperview()
                make.right.equalToSuperview()
                make.top.equalTo(headView)
            }
        }
            
    
      
        
        
        
        tbinfo_V.snp.makeConstraints { (make) in
            make.left.equalTo(self.view)
            make.right.equalTo(self.view)
            if self.listType == .JP {
                make.top.equalTo(jpTitleView.snp.bottom)
            } else {
                make.top.equalTo(zbTitleView.snp.bottom)
            }
             
            
         
        }
        
        zbLine.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(10)
            make.right.equalTo(self.view).offset(-10)
            make.top.equalTo(self.tbinfo_V.snp.bottom).offset(20)
            make.height.equalTo(1)
        }
        
        zbInstructions.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.width.equalTo(110)
            make.top.equalTo(self.tbinfo_V.snp.bottom).offset(5)
            make.height.equalTo(30)
        }
        
        headView.addSubview(webV)
        webV.snp.makeConstraints { (make) in
            make.left.equalTo(zbLine)
            make.right.equalTo(zbLine)
            make.height.equalTo(30)
            make.top.equalTo(self.zbInstructions.snp.bottom).offset(5)
        }
        
        
        
        webV.navigationDelegate = self
        
        tableView.tableFooterView = UIView()
        
        
      
        
        self.pageNetwork()
        
        NotificationCenter.default.addObserver(self, selector: #selector(pageNetwork), name: NSNotification.Name(rawValue: CALL_tenderinfo_REFRESH), object: nil)
        
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(servertimeNotification(_:)), name: Notification.Name("servertime_notification"), object: nil)

    
        
        NotificationCenter.default.addObserver(self, selector: #selector(newestBillStatusNotification(_:)), name: Notification.Name(newestBillStatus_notification), object: nil)

      
      }
      @objc func newestBillStatusNotification(_ notification: Notification) {
          // 从通知中获取用户信息
          if let userInfo = notification.userInfo,
             let arr = userInfo["newestBillStatus_data"] as? [NewestModel_Z] {
       
             
                  let ddd = arr.filter{$0.idKey == self.one.idKey}
                  
                  if ddd.count > 0 {
                      self.one.zParallel = ddd.first!.zParallel
                      if ddd.first!.zEndDate.unwrap != "" {
                          self.one.zEndDate = ddd.first!.zEndDate
                      }
                      if ddd.first!.zOvertimedNum.unwrap != "" {
                          self.one.zOvertimedNum = ddd.first!.zOvertimedNum
                      }
                      self.one.zBidCount = ddd.first!.zBidCount
                      self.one.zMaxPrice = ddd.first!.zMaxPrice
                      self.one.zMyPriceRank = ddd.first!.zMyPriceRank
                  }
                  self.showSome()
              
             
      
       
          }
      }
    var handleStatus = "1" {
        didSet {
            if oldValue != handleStatus {
                self.pageNetwork()
            }
        }
    }
    //  1未开始 2进行中  3已结束
    @objc func servertimeNotification(_ notification: Notification) {
        // 从通知中获取用户信息
        if let userInfo = notification.userInfo,
           let valueServerDate = userInfo["servertime_data"] as? Date {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            var endDate = Date()
            if let endD = dateFormatter.date(from: self.one.zEndDate.unwrap) {
                endDate = endD
            }
            var startDate = Date()
            if let startD = dateFormatter.date(from: self.one.zBeginDate.unwrap) {
                startDate = startD
            }
            let timeNowToEnd = Int(endDate.timeIntervalSince1970-valueServerDate.timeIntervalSince1970)
            let timeNowToStart = Int(startDate.timeIntervalSince1970-valueServerDate.timeIntervalSince1970)
            var timeTipStr:String = ""
            if timeNowToStart > 0 {
                self.handleStatus = "1"
                timeTipStr = "\(self.one.zBeginDate.unwrap)开始"
            } else if timeNowToEnd < 0 {
                self.handleStatus = "3"
                timeTipStr = "\(self.one.zEndDate.unwrap)结束"
                if timeNowToEnd > -15 && timeNowToEnd%3 == 0 {
                    
                    self.pageNetwork()
                }
            } else {
                self.handleStatus = "2"
                // 进行中
                let nowtt = Date.nowTimeToSecond
                let svvvStr = dateFormatter.string(from: valueServerDate)
                timeTipStr = "距结束" + Date.getHHMMSSFormSS(seconds: timeNowToEnd)
            }
     
            self.timeflagView.setTimeFlagInfo(status: btnName, countDown: timeTipStr,model: one)
        
 
        }
    }
    // 获取网络
    @objc func pageNetwork() {
        var api:API!
        
                if listType == .TB {
                    api = API.tender(.queryMytenderZbInfo(id_key: idkey))
                } else {
                    api = API.tender(.queryMytenderJpInfo(id_key: idkey))
                }
        
        KSNetwork.shared.doRequest(api) { (data:BaseResult<ZyaZtbContentModel>) in
            if data.flag == TRUE {
                // 完成掉推送跳转的任务了
                waitGo2Model = WaitModel(complete: true, type: 0 , id: "")
                
                
                if let info = data.infoObjCombine {
                    self.one = info
                    
                    self.jpTitleView.showBannerImg(one: info)
                    self.zbTitleView.showBannerImg(one: info)

                    
                
                    self.showSome()
                    
                    
                    
                    self.btnName = getZBJPStatus(listType: self.listType, auditmark: intTran(info.zAuditMark), status: intTran(info.zStatus), tbType: self.innerType!)
                    
               
                    
                    /// 招出价或者为你推荐  可以出价
                    if (self.innerType == .zbListKHW || self.innerType == .recommendKHW || self.innerType == .jpListKHW || self.innerType == .tbMytbKHW) && (USERINFO.usrid.unwrap != info.zStaffId.unwrap) {
                        
                        
                        //1.判断是否自己发布的 是的话隐藏按钮 用登录返回的usrid和接口返回的z_staff_id比较
                        //
                        //2.z_audit_mark=0 2 9的时候按钮不能点击  文字为未开始
                        //
                        //3.z_audit_mark=1的时候 用z_status判断
                        //以下
                        //4.z_status=0 未开始 不可点击  z_status=1 3 已结束 不可点击
                        //
                        //5.z_status=2  用z_tb_id判断  z_tb_id为空显示出价  不为空显示编辑
                        //
                        //
                        //6.z_status=2 这个你还得根据z_max_bid_no是否为0 去判断要不要加剩余次数
                        
                        
                        if info.zAuditMark.unwrap == "0" || info.zAuditMark.unwrap == "2" || info.zAuditMark.unwrap == "9" {
                            self.configZBBottom(listType: self.listType,true,self.btnName,zyagetRest4Show(max: info.zMaxBidNo.unwrap, rest: info.zRestBidNo.unwrap))
                        } else if info.zAuditMark.unwrap == "1" {
                            if info.zStatus.unwrap == "0" {
                                self.configZBBottom(listType: self.listType,true,"未开始",zyagetRest4Show(max: info.zMaxBidNo.unwrap, rest: info.zRestBidNo.unwrap))
                            } else if info.zStatus.unwrap == "1" || info.zStatus.unwrap == "3" {
                                self.configZBBottom(listType: self.listType,true,"已结束",zyagetRest4Show(max: info.zMaxBidNo.unwrap, rest: info.zRestBidNo.unwrap))
                            } else if info.zStatus.unwrap == "2" {
                                
                                // 查询现有保证金余量
                                self.getDepositValue { (flag,value) in
                                    if flag {
                                        self.depositRemain = doubleTran(value)
                                        var showName = ""
                                        var judgeID = ""
                                        if self.innerType == .jpListKHW {
                                            showName = "销售出价"
                                            judgeID = info.zBidId.unwrap
                                        } else {
                                            showName = "出价"
                                            judgeID = info.zTbId.unwrap
                                        }
                                        if self.depositRemain >= info.zDepositMoney.doubleWrap { // （保证金足够）
                                            
                                            if judgeID.isEmpty {
                                                // 没id 说明是新的
                                                self.configZBBottom(listType: self.listType,true,showName,zyagetRest4Show(max: info.zMaxBidNo.unwrap, rest: info.zRestBidNo.unwrap))
                                            } else {
                                                // 有id 说明是投过的，显示编辑
                                                self.configZBBottom(listType: self.listType,true,"编辑",zyagetRest4Show(max: info.zMaxBidNo.unwrap, rest: info.zRestBidNo.unwrap))
                                            }
                                        } else {
                                            // 保证金不足
                                            if let remain = info.zRemainTry {
                                                if remain == "0" {
                                                    self.configZBBottom(listType: self.listType,true,"缴纳保证金","")
                                        
                                                    
                                                } else {
                                                    self.configZBBottom(listType: self.listType,true,"试投","(剩余\(remain)次)",id:judgeID)
                                                }
                                            } else {
                                                self.configZBBottom(listType: self.listType,true,"缴纳保证金","")
                                            }
                                            
                                            
                                            
                                            
                                            
                                        }
                                    } else { // 错误，一般为未开通保证金账户
                                        self.configZBBottom(listType: self.listType,true,"缴纳保证金","")
                                    }
                                    
                                }
                                
                                
                                
                                
                            } else {
                                self.configZBBottom(listType: self.listType,false)
                            }
                        } else {
                            self.configZBBottom(listType: self.listType,false)
                        }
                        
                    } else { // 其他不能出价
                        self.configZBBottom(listType: self.listType,false)
                    }
                    
               
                    let dsstr = self.helper.getContentStr(listType: self.listType, info: info)
                    
//                    self.tbinfo_V.contentStr = self.helper.getContentStr(listType: self.listType, info: info)
                    self.tbinfo_V.content1.multiLineTitleContentShow(contentStr: dsstr, fontx: 16)
                    self.tbinfo_V.ks_height = self.tbinfo_V.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
                    self.originalMark = info.ztbMark
                    
                    if info.zInvited.unwrap == "1" {
                        // 如果有邀标标志，展示邀标按钮
                        self.navigationItem.rightBarButtonItem = self.helper.configRightItem4Tender(listType:self.listType) {
                            self.helper.getInviteListAction(listType: self.listType, fromVC: self, z_zb_id: self.idkey)
                        }
                    }
           
                    self.webV.loadHTMLString(adaptHtml(info.zContent.unwrap), baseURL: nil)
                    let imgNm = info.ztbMark == "1" ? "shoucang_red" : "shoucang"
                    self.btn_mark.setImage(UIImage(named: imgNm), for: .normal)
                    
                    
                    if let files = info.zbFile {
                        
                        
                        self.zbFiles = files
                        let hasPictureArr = self.zbFiles.filter{ $0.zType == "0" }
                        
                        // 创建调度组
                        let workingGroup = DispatchGroup()
                        
                        for i in 0..<self.zbFiles.count {
                            
                            if self.zbFiles[i].zType == "2" { // 视频
                                
                                let ggUrl = self.zbFiles[i].zPicUrl.unwrap.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
                                let  vedioImg = self.getFirstFrame(url: "\(ggUrl)")
                                self.zbFiles[i].imageV = vedioImg
                                
                            } else if self.zbFiles[i].zType == "0" { // 图片
                                
                                
                                let btn = UIImageView()
                                btn.contentMode = .scaleAspectFit
                                btn.tag = i
                                let ggUrl = self.zbFiles[i].zPicUrl.unwrap.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
                                if  let imageUrl = URL(string:"\(ggUrl)") {
                                    let resource = KF.ImageResource(downloadURL: imageUrl)
                                    // 入组
                                    workingGroup.enter()
                                    btn.kf.setImage(with: resource, placeholder: UIImage(named:"defaultImg_content"),completionHandler: {
                                        (kfresult:Result<RetrieveImageResult, KingfisherError>) in
                                        workingGroup.leave()
                                    })
                                } else {
                                    btn.image = UIImage(named:"defaultImg_content")
                                }
                                
                                self.zbFiles[i].imageV = btn
                                
                            } else {
                                let btn = ZyaFileButton()
                                btn.tag = i
                                btn.setTitle(files[i].zName, for: .normal)
                                btn.addTarget(self, action: #selector(self.fileBtnAction(sender:)), for: .touchUpInside)
                                self.zbFiles[i].fileBtn = btn
                            }
                            
                        }
                        if hasPictureArr.count == 0 {
                            self.preMakeCon()
                        }
                        
                        // 调度组里的任务都执行完毕
                        workingGroup.notify(queue: .main) {
                            
                            self.preMakeCon()
                        }
                        
                        
                    }
                    
                }
                if self.listType == .JP {
                    
                    self.insertIds2Update()
                
                     
                }
            } else {
                
            }
        }
        
    }
    func insertIds2Update() {
        
        GetNewestUtil_Z.shared.appendIds(ids: [self.idkey],type: self.listType)
 
    }
    func showSome() {
        
        self.jpTitleView.recordApi = API.tender(.queryBidRecordList(z_zb_id: one.idKey.unwrap, z_bid_id: one.zBidId.unwrap, z_staff_id: USERINFO.usrid.unwrap))
        
        self.jpTitleView.setChujiaShow(title: one.zTitle.unwrap, count: one.zBidCount.unwrap, price: one.zMyPrice.unwrap,unit: one.zLeastUnitNm.unwrap, rank: one.zMyPriceRank.unwrap,z_end_price_rank: one.zEndPriceRank.unwrap,z_parallel: self.one.zParallel.unwrap)
        
        self.zbTitleView.recordApi = API.tender(.queryTbRecordList(z_zb_id: one.idKey.unwrap, z_bid_id: one.zBidId.unwrap, z_staff_id: USERINFO.usrid.unwrap))

        self.zbTitleView.setChujiaShow(title: one.zTitle.unwrap, count: one.zBidCount.unwrap, price: one.zMyPrice.unwrap,unit: one.zUnitNm.unwrap, rank: one.zMyPriceRank.unwrap,z_end_price_rank: one.zEndPriceRank.unwrap,z_parallel: self.one.zParallel.unwrap)

        
        
    }
    func preMakeCon() {
        self.makeImgVedioConstr()
        self.showFinalheaderHeight()
    }
    
    // 给图片和视频布局
    func makeImgVedioConstr() {
        self.imgHeight = 0
        //        for subV in self.headView.subviews {
        //            if subV.isMember(of: FileButton.self) || subV.isMember(of: UIImageView.self) {
        //                subV.removeFromSuperview()
        //            }
        //        }
        let fileArr = self.zbFiles.filter{ $0.fileBtn.isSome }
        let imageArr = self.zbFiles.filter{ $0.imageV.isSome }
        
        for i in 0..<fileArr.count {
            let fileBtn = fileArr[i].fileBtn!
            
            self.headView.addSubview(fileBtn)
            self.imgHeight! += 30
            fileBtn.snp.makeConstraints { (make) in
                if i == 0 {
                    make.top.equalTo(self.webV.snp.bottom).offset(6)
                } else {
                    make.top.equalTo(fileArr[i - 1].fileBtn!.snp.bottom).offset(6)
                }
                make.width.equalTo(KSGlobal.screenW)
                make.height.equalTo(30)
                make.centerX.equalTo(self.headView)
            }
        }
        for i in 0..<imageArr.count {
            let imageV = imageArr[i].imageV!
            self.headView.addSubview(imageV)
            if imageArr[i].zType == "2" {
                imageV.isUserInteractionEnabled = true
                let tap = UITapGestureRecognizer()
                tap.numberOfTapsRequired = 1
                tap.addTap { [unowned self,i]  _ in
                    let file = imageArr[i]
                    let cwebV = CommonWebController()
                    let str1 = "\(file.zPicUrl.unwrap)"
                    cwebV.reportUrl = str1
                    cwebV.title = file.zName.unwrap
                    self.navigationController?.pushViewController(cwebV, animated: true)
                    
                }
                
                imageV.addGestureRecognizer(tap)
                
                let v_start = UIImageView()
                v_start.image = UIImage(named: "vedio_start")
                imageV.addSubview(v_start)
                v_start.snp.makeConstraints { make in
                    make.bottom.right.equalTo(imageV).offset(-10)
                    make.width.equalTo(50)
                    make.height.equalTo(50)
                }
            }
            var scale:CGFloat = 1
            if let imggg = imageV.image {
                scale = imggg.size.height / imggg.size.width
            }
            if scale > 2.5 {
                scale = 2.5 // 控制一下比例最大值，防止非常长
            }
            
            self.imgHeight! += Double(KSGlobal.screenW * scale)
            imageV.snp.makeConstraints { (make) in
                if i == 0 {
                    if fileArr.count == 0 {
                        make.top.equalTo(self.webV.snp.bottom).offset(6)
                    } else {
                        make.top.equalTo(fileArr[fileArr.count - 1].fileBtn!.snp.bottom).offset(6)
                    }
                } else {
                    make.top.equalTo(imageArr[i - 1].imageV!.snp.bottom).offset(6)
                }
                make.height.equalTo(KSGlobal.screenW * scale)
                make.width.equalTo(KSGlobal.screenW)
                make.centerX.equalTo(self.headView)
                
            }
        }
        
    }
    
    
    /// withOpBtn 是否带右侧操作按钮
    func configZBBottom(listType:TBandJPType,_ withOpBtn:Bool,_ btnName:String? = "",_ cishuDesc:String? = "",id:String = "") {
      
         if btn_tb.superview.isSome { // 重置状态先移除操作按钮
            btn_tb.removeFromSuperview()
        }
        if btn_mark.superview.isSome { // 重置状态先移除操作按钮
            btn_mark.removeFromSuperview()
        }
     
        if btn_feedback.superview.isSome { // 重置状态先移除操作按钮
            btn_feedback.removeFromSuperview()
        }
        if btn_call.superview.isSome { // 重置状态先移除操作按钮
            btn_call.removeFromSuperview()
        }
        var chirds = [(UIButton,CGSize)]()
        
        let opWidth:CGFloat = 45
        let tbWidth:CGFloat = withOpBtn ? 130 : 0
        
        
        bottomView.addSubview(btn_mark)
        chirds.append((btn_mark,CGSize(width: opWidth, height: 54)))
        
        if listType == .TB {
//            bottomView.addSubview(btn_down)
//            chirds.append((btn_down,CGSize(width: opWidth, height: 54)))
        } else {
            bottomView.addSubview(btn_feedback)
            chirds.append((btn_feedback,CGSize(width: opWidth, height: 54)))
        }
        
        bottomView.addSubview(btn_call)
        chirds.append((btn_call,CGSize(width: opWidth, height: 54)))
        // 要求带按钮且不是访客
        if withOpBtn && !isFangke() && btnName.unwrap != "" {
            bottomView.addSubview(btn_tb)
            chirds.append((btn_tb,CGSize(width: tbWidth, height: 40)))
        }
        
        
        // 控件间距
        let subWidths = chirds.compactMap{ $0.1.width }.reduce(0, +)
        let marginx = (KSGlobal.screenW - subWidths) / CGFloat(chirds.count + 1)
        var lastX = marginx
        for one in chirds {
            one.0.frame.size = one.1
            one.0.ks_x = lastX
            lastX = lastX + one.1.width + marginx
            one.0.ks_centerY = 30
        }
        
        
        if btnName.unwrap == "进行中" || btnName.unwrap == "出价" {
            btn_tb.setTitle("出价\(cishuDesc!)", for: .normal)
            btn_tb.tag = 101
            btn_tb.addTarget(self, action: #selector(clickAction(sender:)), for: .touchUpInside)
        } else if  btnName.unwrap == "销售出价" {
            btn_tb.setTitle("出价\(cishuDesc!)", for: .normal)
            btn_tb.tag = 102
            btn_tb.addTarget(self, action: #selector(clickAction(sender:)), for: .touchUpInside)
        }  else if btnName.unwrap == "编辑" {
            btn_tb.setTitle("编辑\(cishuDesc!)", for: .normal)
            btn_tb.tag = 106
            btn_tb.addTarget(self, action: #selector(clickAction(sender:)), for: .touchUpInside)
            
        } else if btnName.unwrap == "缴纳保证金" {
            btn_tb.setTitle("缴纳保证金", for: .normal)
            btn_tb.tag = 107
            btn_tb.addTarget(self, action: #selector(clickAction(sender:)), for: .touchUpInside)
        } else if btnName.unwrap == "试投" {
            
            if self.listType == .TB {
                btn_tb.setTitle("试投\(cishuDesc!)", for: .normal)
                btn_tb.tag = id.isEmpty ?  101 : 106
            } else {
                btn_tb.setTitle("试拍\(cishuDesc!)", for: .normal)
                btn_tb.tag = id.isEmpty ? 102 : 106
            }
            btn_tb.addTarget(self, action: #selector(clickAction(sender:)), for: .touchUpInside)
        }  else {
            btn_tb.setTitle(btnName.unwrap, for: .normal)
        }
        
        
        
    }
    @objc func editAction(sender:UIButton) {
        
        let copyoneDic = self.one.dictionaryRepresentation()
        let copyone = ZyaZtbContentModel(JSON:copyoneDic)

        
        self.helper.go2TenderTbController(listType: self.listType, controller:self,z_tb_id:one.zTbId.unwrap,z_zb_id:self.idkey,z_bid_id: self.one.zBidId.unwrap,excuteType:.fix,model:copyone) {
            self.pageNetwork()
        }
    }
    @objc func baozhengjinAction(sender:UIButton) {
        let result =  userDefault.value(forKey: USERINFO.usrid.unwrap + self.idkey) as? String
        if result == "1" { // 阅读过协议了
            
            self.helper.go2DepositController(controller: self)
            
        } else {
            
            let vc = ZyaAgreementVC.initWithNav(z_zb_id: self.idkey) { passflag in
                
                if passflag {
                    self.helper.go2DepositController(controller: self)
                }
                
            }
            self.present_FullScreen(to: vc)
            
        }

    }
    @objc func clickAction(sender:UIButton) {
        
        guard !isFangke() else {
            KSToast("访客无权限")
            return
        }
        guard !(sender.titleLabel?.text == "已结束") else {
            return
        }
        
        switch sender.tag {
        case 107:
            self.baozhengjinAction(sender:sender)
        case 106:
            self.editAction(sender:sender)
        case 101,102:
            
            let copyoneDic = self.one.dictionaryRepresentation()
            let copyone = ZyaZtbContentModel(JSON:copyoneDic)
          
            
            let result =  userDefault.value(forKey: USERINFO.usrid.unwrap + self.idkey) as? String
            if result == "1" { // 阅读过协议了
                
                self.helper.go2TenderTbController(listType: self.listType,controller: self, z_zb_id: self.idkey,z_bid_id: self.one.zBidId.unwrap, excuteType: .add,model:copyone) {
                    self.pageNetwork()
                }
                
            } else {
                
                let vc = ZyaAgreementVC.initWithNav(z_zb_id: self.idkey) { passflag in
                    
                    if passflag {
                        self.helper.go2TenderTbController(listType: self.listType,controller: self, z_zb_id: self.idkey,z_bid_id: self.one.zBidId.unwrap, excuteType: .add,model:copyone) {
                            self.pageNetwork()
                        }
                    }
                    
                    
                }
                self.present_FullScreen(to: vc)
                
            }
         
     
        default:
            break
        }
    }
    
    
    
    
    @objc func fileBtnAction(sender:UIButton) {
        let file = self.zbFiles[sender.tag]
        let cwebV = CommonWebController()
        let str1 = "\(file.zPicUrl.unwrap)"
        cwebV.reportUrl = str1
        cwebV.title = file.zPicUrl.unwrap
        self.navigationController?.pushViewController(cwebV, animated: true)
        
    }
    @objc func feedbackAction() {
        self.helper.go2FeedbackForm(zZbId: self.one.idKey.unwrap, zZbNo: self.one.zRecordNo.unwrap, zTitle: self.one.zTitle.unwrap,controller: self)
 
        
    }
    
    @objc func downloadAction() {
        
        self.helper.downloadFiles(zbFiles: self.zbFiles)
        
        
    }
    @objc func markAction() {
        if self.one.ztbMark == "1" {
            self.one.ztbMark = "0"
            self.btn_mark.setImage(UIImage(named: "shoucang"), for: .normal)
        } else {
            self.one.ztbMark = "1"
            self.btn_mark.setImage(UIImage(named: "shoucang_red"), for: .normal)
        }
        
        
    }
    
    @objc func phoneAction(sender:UIButton) {
        
        
        if self.btnflag == "1" {
            
            self.btnflag = "0"
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                self.btnflag = "1"
            }
            
            
            let phone = "tel://" + one.zTel.unwrap
            if UIApplication.shared.canOpenURL(URL(string: phone)!) {
                
                UIApplication.shared.open(URL(string: phone)!, options: [:], completionHandler: { result in
                })
                
            } else {
                KSToast("电话错误")
            }
            
        }
        
        
        
    }
    func getFirstFrame(url:String) -> UIImageView {
        let thumb = UIImageView()
        if let urlx = URL.init(string: url) {
            let asset = AVURLAsset.init(url: urlx, options: nil)
            let gen = AVAssetImageGenerator.init(asset: asset)
            gen.appliesPreferredTrackTransform = true
            let time = CMTimeMake(value: Int64(0.0), timescale: 1)
            var actualTime : CMTime = CMTimeMake(value: Int64(0.0), timescale: 0)
            do {
                let image = try gen.copyCGImage(at: time, actualTime: &actualTime)
                thumb.image = UIImage.init(cgImage: image)
            } catch  {
                thumb.image = UIImage(named:"defaultImg_content")
            }
        } else {
            thumb.image = UIImage(named:"defaultImg_content")
        }
        return thumb
    }
}

extension ZyaTenderInfoVC: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        var webheightx = 0.0
        self.webV.evaluateJavaScript("document.documentElement.clientHeight") { [unowned self] (result, error) in
            
            if let tempHeight: Double = result as? Double {
                webheightx = tempHeight
            }
            DispatchQueue.main.async { [unowned self] in
                
                let endRect = zyadealwithHeight(height: webheightx, rect: self.webV.frame)
                self.webV.snp.remakeConstraints { (make) in
                    make.left.equalTo(self.zbLine)
                    make.right.equalTo(self.zbLine)
                    make.height.equalTo(webheightx)
                    make.top.equalTo(self.zbInstructions.snp.bottom).offset(5)
                }
                self.webHeight = webheightx
                KSLog("走web")
                KSLog("\(self.webHeight)")
                self.showFinalheaderHeight()
                
            }
        }
        
        
        
    }
    // 最终高度
    func showFinalheaderHeight() {
        var wh:Double = 0
        var ih:Double = 0
        if let webHeight = self.webHeight {
            wh = webHeight
         }
        if let imgHeight = self.imgHeight {
            ih = imgHeight
        }
        self.headView.ks_height = self.helper.getHeaderHeight(webheight: wh,imgHeight:ih)
        self.tableView.reloadData()
    }
    
}



/// 最大为0 时 ，不显示剩余次数，否则显示 剩余次数
func zyagetRest4Show(max:String,rest:String) -> String {
    if max == "0" {  // 无限次，随便保存，不用显示
        return ""
    } else {  // 有限次， 可以保存
        return "(剩余\(rest)次)"
    } // 次数用完了
}
// 用最大次数和剩余次数判断是否可操作
func zyagetRest4Judge(max:String,rest:String) -> Bool {
    if max == "0" {
        return true
    } else if rest != "0" {
        return true
    } else {
        return false
    }
}





class ZyaOpButton:UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setTitleColor(.darkGray, for: .normal)
        self.titleLabel?.textAlignment = .center
        self.titleLabel?.font = UIFont.systemFont(ofSize: 13)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        let width_r = self.frame.width * 0.7
        // 设置imageView
        imageView?.frame = CGRect(x: (self.frame.size.width - width_r)/2 , y: 0, width: width_r, height: width_r)
        // 设置title
        titleLabel?.frame = CGRect(x: 0 , y: self.frame.height/2, width: self.frame.width, height: self.frame.height/2)
        
        
    }
}


class ZyaActionButton:UIButton{
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        self.layer.cornerRadius = 20
        self.setTitleColor(.white, for: .normal)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func setTitle(_ title: String?, for state: UIControl.State) {
        super.setTitle(title, for: state)
        if title.unwrap.count > 8 {
            self.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        } else if title.unwrap.count > 5 {
            self.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        } else {
            self.titleLabel?.font = UIFont.systemFont(ofSize: 16)
            
        }
        
        if title.unwrap == "已结束" || title.unwrap == "未开始" {
            self.backgroundColor = #colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
        } else if title.unwrap.contains("编辑") {
            self.backgroundColor = .red
        } else if title.unwrap.contains("试") {
            self.backgroundColor = Theme.primaryColor()
        } else {
            self.backgroundColor = .red
        }
        
        
    }
}
